package com.winexpress.session.product;

import com.winexpress.entity.Comment;
import com.winexpress.entity.User;
import com.winexpress.entity.Wine;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@LocalBean
public class CommentSessionBean {

    @PersistenceContext
    private EntityManager em;

//  public Long createComment(Long uid, Long wid, String comment, String nature) {
    public Long createComment(Comment inComment) {
        Long uid = inComment.getId();
        Long wid = inComment.getWid();
        String comment = inComment.getComment();
        String nature = inComment.getNature();

        Comment newComment = new Comment();

        User u = em.find(User.class, uid);
        newComment.setUid(u);
        newComment.setComment(comment);
        newComment.setNature(nature);
        newComment.setWid(wid);
        java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
        newComment.setCommentDate(date);

        em.persist(newComment);
        em.flush();

        Wine w = em.find(Wine.class, wid);
        List<Comment> list = w.getComments();
        list.add(newComment);
        w.setComments(list);

        em.persist(w);
        em.flush();

        return newComment.getId();
    }

    public List<Comment> getProductComment(long wid) {
        Wine wine = em.find(Wine.class, wid);
        return wine.getComments();
    }

    public void deleteComment(Long commentID) {
        Comment comment = em.find(Comment.class, commentID);
        Long wid = comment.getWid();
        Wine wine = em.find(Wine.class, wid);

        wine.getComments().remove(comment);
        em.remove(comment);

        em.persist(wine);
        em.flush();
    }
}
